﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XmlSplitter
{
    internal class XmlJoin
    {
        private List<string> files;
        private string finalFileName;
        private XName insertToElement;
        private string rootElement;
        private string xmlTag;
        private string Dir;
        public List<XElement> Elements { get; private set; }

        public XmlJoin(string xmlTag, List<string> files, string dir, string finalFileName)
        {
            this.xmlTag = xmlTag;
            this.files = files;
            this.finalFileName = finalFileName;
            this.Dir = dir;
        }


        public void Exec()
        {
            if (!string.IsNullOrEmpty(Dir))
            {
                files.AddRange(new DirectoryInfo(Dir).GetFiles("*.xml").Select(s => s.FullName));
                files = files.Distinct().ToList();
            }
            for (int i = 0; i < files.Count; i++)
            {
                if (i == 0)
                {
                    Init(files[i]);
                }
                else
                {
                    AppendElements(files[i]);
                }
            }

            FinalizeXML();
        }

        private void FinalizeXML()
        {
            var final = XDocument.Parse(rootElement);
            final.Descendants(insertToElement).Single().Add(Elements);
            JoinToFile(final);
        }

        private void JoinToFile(XDocument final)
        {
            File.WriteAllText(finalFileName, final.ToString(), Encoding.Default);
        }

        private void AppendElements(string filename)
        {
            XDocument xDoc = Tools.GetXDoc(filename);
            Elements.AddRange(xDoc.Descendants(Tools.GetXName(xmlTag, xDoc)).ToList());
        }

        public void Init(string filename)
        {
            XDocument xDoc = Tools.GetXDoc(filename);
            rootElement = Tools.PrepareClearRoot(xDoc, xmlTag, out insertToElement);
            Elements = xDoc.Descendants(Tools.GetXName(xmlTag, xDoc)).ToList();
        }

        
    }
}